package src.main.java.com.pms.gui.dialog;

import javax.swing.*;
import java.awt.*;
import src.main.java.com.pms.service.PetBasicService;

public class AddPetDialog extends JDialog {
    private JTextField nameField;
    private JTextField typeField;
    private JTextField ageField;
    private PetBasicService petService;

    public AddPetDialog(JFrame parent) {
        super(parent, "添加宠物", true);
        petService = new PetBasicService();
        initComponents();
    }

    private void initComponents() {
        setSize(400, 300);
        setLocationRelativeTo(getParent());

        JPanel panel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        // 宠物名称
        gbc.gridx = 0;
        gbc.gridy = 0;
        panel.add(new JLabel("宠物名称:"), gbc);

        gbc.gridx = 1;
        nameField = new JTextField(20);
        panel.add(nameField, gbc);

        // 宠物类型
        gbc.gridx = 0;
        gbc.gridy = 1;
        panel.add(new JLabel("宠物类型:"), gbc);

        gbc.gridx = 1;
        typeField = new JTextField(20);
        panel.add(typeField, gbc);

        // 宠物年龄
        gbc.gridx = 0;
        gbc.gridy = 2;
        panel.add(new JLabel("宠物年龄:"), gbc);

        gbc.gridx = 1;
        ageField = new JTextField(20);
        panel.add(ageField, gbc);

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(e -> handleAddPet());

        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.gridwidth = 2;
        panel.add(addButton, gbc);

        add(panel);
    }

    private void handleAddPet() {
        try {
            String name = nameField.getText().trim();
            String type = typeField.getText().trim();
            int age = Integer.parseInt(ageField.getText().trim());

            if (name.isEmpty() || type.isEmpty()) {
                JOptionPane.showMessageDialog(this, "请填写所有字段！", "错误", JOptionPane.ERROR_MESSAGE);
                return;
            }

            if (petService.addPet(name, type, age)) {
                JOptionPane.showMessageDialog(this, "添加成功！");
                dispose();
            } else {
                JOptionPane.showMessageDialog(this, "添加失败！", "错误", JOptionPane.ERROR_MESSAGE);
            }
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(this, "年龄必须是数字！", "错误", JOptionPane.ERROR_MESSAGE);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(this, "添加失败：" + e.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }
} 